import React, { Component } from 'react';
import {
  Card,
  Button,
  Table,
  Menu,
  Input,
  Divider,
  Popconfirm,
  Modal,
  message
} from 'antd';
import { connect } from 'dva';
import PartItem from './components/Part';
import WareHousing from './components/WareHousing';
import config from '../../../config/web.config';
import styles from './index.less';
import { getValueWithLocalStorage, getOwner } from '@/utils/authority';
import defaultPic from '@/assets/default.png'

const namespace = 'Inventory';

const mapStateToProps = state => {
  const list = state[namespace].goodsList;
  const isLoading = state[namespace].goodsLoading;
  return {
    list,
    isLoading,
  };
};

const mapDispatchToProps = dispatch => {
  return {
    getList: (params) => {
      const action = {
        type: `${namespace}/queryGoods`,
        payload: {
          ...params,
          owner: getOwner(),
        },
      };
      dispatch(action);
    },
    saveItem: (values) => {
      const action = {
        type: `${namespace}/saveGoods`,
        payload: {
          ...values,
          owner: getOwner(),
        },
      };
      return dispatch(action);
    },
    editItem: (values) => {
      const action = {
        type: `${namespace}/editGoods`,
        payload: {
          ...values,
        },
      };
      return dispatch(action);
    },    
    delItem: (_id) => {
      const action = {
        type: `${namespace}/delGoods`,
        payload: {
          id: _id,
        },
      };
      return dispatch(action);
    },
    inoutRecord: (values1, values2) => {
      const action = {
        type: `${namespace}/inoutRecord`,
        payload1: {
          ...values1,
        },
        payload2: {
          ...values2,
        }
      };
      return dispatch(action);
    }
  };
};

@connect(
  mapStateToProps,
  mapDispatchToProps
)
export default class ContactList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      itemData: {},
      modalLoading: false,
      wareModalVisible: false,
      wareModalLoading: false,
      key: ''
    };
    // this.formRef = React.createRef();
  }

  componentDidMount() {
    config.loadlCNZZ()
    this.reloadData();
  }

  reloadData = () => {
    const { key } = this.state;
    this.props.getList({ key });
  };

  // 新建
  handleCreateItem = (event) => {
    event.preventDefault();
    this.setState({
      modalVisible: true,
      itemData: { }
    });
  }

  // 编辑
  handleEditItem = (record, event) => {
    event.preventDefault();
    this.setState({
      modalVisible: true,
      itemData: record
    });
  }

  handleDelItem = (id) => {
    this.props.delItem(id).then(res => {
      if(res.code === 1){
        message.success("删除配件成功");
        this.reloadData();
      }else{
        message.error( res.msg || "删除配件失败");
      }
    });
  }

  handleModalOk = () => {
    this.formInstance.handleSubmit();
  }

  handleModalCancel = () => {
    this.setState({
      modalVisible: false,
    });
  }

  handleSaveForm = (values) => {
    const { editItem, saveItem } = this.props;
    this.setState({
      modalLoading: true
    });
    if(values.id){
      editItem(values).then(res => {
        if(res.code === 1){
          message.success("编辑配件成功");
          this.setState({
            modalVisible: false,
            modalLoading: false,
            itemData: {}
          }, this.reloadData);
        }else{
          message.error( res.msg || "编辑配件失败");
          this.setState({
            modalLoading: false,
          });
        }
      })
    }else{
      saveItem(values).then(res => {
        if(res.code === 1){
          message.success("新增配件成功");
          this.setState({
            modalVisible: false,
            modalLoading: false,
            itemData: {}
          }, this.reloadData);
        }else{
          message.error( res.msg || "新增配件失败");
          this.setState({
            modalLoading: false,
          });
        }
      })
    }
  }

  handleWareModalShow = (record, event) => {
    event.preventDefault();
    this.setState({
      wareModalVisible: true,
      itemData: record
    });
  }

  handleWareHousingOk = () => {
    this.formInstance2.handleSubmit();
  }

  handleWareModalCancel = () => {
    this.setState({
      wareModalVisible: false,
    });
  }

  handleSaveWareHousing = (values) => {
    const { inoutRecord } = this.props;
    const { itemData } = this.state;
    this.setState({
      wareModalLoading: true
    });
    const oldNum = parseInt(itemData.num);
    const oldPrice = parseInt(itemData.systemprice);
    const newNum = parseInt(values.num);
    const newPrice = parseInt(values.price);
    const totalNum = oldNum + newNum;
    const systemprice = (oldNum * oldPrice + newNum * newPrice) / totalNum
    const updateValues = {
       "systemprice": (systemprice || 0).toFixed(2),
       "num": totalNum,
       "id": itemData._id,
       "purchasenum":"0"
    }
    const insertValues = {
      "owner": getOwner(),
      "num": totalNum,
      "dealer": values.dealer,
      "goods": itemData._id,
      "remark":"",
      "type":"1"
    }
    inoutRecord(updateValues, insertValues).then(res => {
      if(res.code === 1){
        message.success("配件入库成功");
        this.setState({
          wareModalVisible: false,
          wareModalLoading: false,
          itemData: {}
        }, this.reloadData);
        this.formInstance2.handleReset();
      }else{
        message.error( res.msg || "配件入库失败");
        this.setState({
          wareModalLoading: false,
        });
      }
    })
  }

  saveInstance = (instance) => {
    this.formInstance = instance;
  }

  saveInstance2 = (instance) => {
    this.formInstance2 = instance;
  }

  render() {
    const columns = [
      {
        title: '图片',
        dataIndex: 'picurl',
        key: 'picurl',
        width: 60,
        render: (text, record) => (
          <img
            className={styles.cell_headurl}
            src={ !text ? defaultPic : config.HttpUrl+'/file/pic/' + (text.indexOf('.png')== -1 ?text+'.png':text)}
          />
        ),
      },
      {
        title: '配件',
        dataIndex: 'name',
        key: 'name',
        width: 150,
      },      
      {
        title: '分类',
        dataIndex: 'category',
        key: 'category',
        width: 150,
        render: (text, record) => {
          return text ? text.name : '---'
        }
      },
      {
        title: '价格',
        dataIndex: 'systemprice',
        key: 'systemprice',
        width: 150,
      },
      {
        title: '库存',
        dataIndex: 'num',
        key: 'num',
        width: 150,
      },
      {
        title: '编码',
        dataIndex: 'barcode',
        key: 'barcode',
        width: 150,
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        width: 160,
        render: (text, record) => (
          <span>
            <a href="#" onClick={(event)=>this.handleWareModalShow(record, event)}>入库</a>
            <Divider type="vertical" />
            <a href="#" onClick={(event)=>this.handleEditItem(record, event)}>编辑</a>
            <Divider type="vertical" />
            <Popconfirm
                  title="确认删除此配件?"
                  onConfirm={ () => this.handleDelItem(record._id) }
                  okText="确认"
                  cancelText="取消"
                >
              <a href="#" className={styles.delBtnStyle}>
                删除
              </a>
            </Popconfirm>
          </span>
        ),
      },
    ];

    const { modalVisible, modalLoading, owner, itemData, wareModalVisible, wareModalLoading } = this.state;
    const { isLoading, list } = this.props;

    const extraContent = (
      <div className={styles.extraContent}>
        <Button type="primary"
          onClick={this.handleCreateItem}
        >新增配件</Button>
      </div>
    );

    return (
      <Card
        bordered={false}
        title={'库存预览'}
        style={{ marginTop: 24 }}
        bodyStyle={{ padding: '1px 0px 0px 0px' }}
        extra={extraContent}
      >
        <Table
          columns={columns}
          loading={isLoading}
          dataSource={list}
          rowKey="_id"
          pagination={false}
        />

        <Modal 
          title={ itemData._id ? "编辑配件" : "新建配件" }
          width={600}
          visible={modalVisible}
          confirmLoading={modalLoading}
          onOk={this.handleModalOk}
          onCancel={this.handleModalCancel}
        >
          <PartItem 
            saveInstance = {this.saveInstance}
            onSaveForm = {this.handleSaveForm}
            data={itemData}
          />
        </Modal>

        <Modal
          title="入库"
          width={600}
          visible={wareModalVisible}
          confirmLoading={wareModalLoading}
          onOk={this.handleWareHousingOk}
          onCancel={this.handleWareModalCancel}
        >
          <WareHousing 
            saveInstance={this.saveInstance2}
            onSaveForm = {this.handleSaveWareHousing}
            data={itemData}
          />
        </Modal>
      </Card>
    );
  }
}